package com.hgzy.meeting.interceptor;

import com.hgzy.meeting.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PermissInterceptor  implements HandlerInterceptor {
    AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {
        //获取uri地址 /doLogin
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        // 如果请求的页面是 主页面 注册页面 登陆页面  就直接放行
        if( "/".equals(requestURI)
                ||"/doLogin".equals(requestURI)
                ||"/doReg".equals(requestURI)
                ||"/register".equals(requestURI)){
            return true;
        }
//        这里获取session对象 里面传参为true防止空指针异常 为true 就算没有 会自己创建session对象
        HttpSession httpSession=request.getSession(true);
//        获取登陆所传入session的键值
        Employee currentUser = (Employee) httpSession.getAttribute("currentUser");
        System.out.println(":"+currentUser);
//        判断是不是管理员用户
    if (antPathMatcher.match("/admin/**",requestURI)){
        // 如果获取到的currentUser不为空 且角色等级为二 就放行
        if (currentUser != null){
            if (currentUser.getRole() == 2){
                return true;
            }else {
                response.getWriter().write("forbiddn");
                response.sendRedirect("/login");
                return  false;
            }

        }

    }else {
//        如果是普通用户 只要不为null 就直接放行
       if (currentUser!=null){
           return  true;
       }
    }
    response.sendRedirect("/");
    return false;

    }
}
